const db = require('../db/index')

// 查询权限列表
exports.getActivityList = (req, res) => {
	const sql = 'select * from authority order by authority_id desc'
	db.query(sql, (err, results) => {
		if(err) return res.cc(err)
		let arr = results
		const sql = 'select * from user'
		db.query(sql, (err, results) => {
			if(err) return res.cc(err)
			results.map(userItem => {
				arr.forEach(item => {
					if(userItem.id === item.a_creater_id){
						item.a_creater_name = userItem.nick_name
					}
				})
			})
			res.send({
				status: 0,
				message: '查询成功',
				data: arr
			})
		})
	})
}

// 更新权限
exports.updateActivity = (req, res) => {
	const sql = 'update authority set ? where authority_id=?'
	db.query(sql, [req.body, req.body.authority_id], (err, results) => {
		if(err) return res.cc(err)
		res.cc('更新成功', 0)
	})
}

// 添加权限
exports.addActivity = (req, res) => {
	const sql = 'select * from authority where a_name=?'
	db.query(sql, req.body.a_name, (err, results) => {
		if(err) return res.cc(err)
		if(results.length === 1){ return res.cc('权限名称重复，请修改') }
		const sql = 'insert into authority set ?'
		db.query(sql, req.body, (err, results) => {
			if(err) return res.cc(err)
			res.cc('添加成功', 0)
		})
	})
}

// 删除权限
exports.deleteActivity = (req, res) => {
	const sql = 'select * from user where id_authority=? and state<2'
	db.query(sql, req.body.authority_id, (err, results) => {
		if(err) return res.cc(err)
		if(results.length > 0){
			let str = ''
			results.map((item, index) => {
				if(index === 0){
					str = item.nick_name
				} else {
					str = str + '、' + item.nick_name
				}
			})
			return res.cc(`${str}等 ${results.length} 人正在使用该权限，请给员工更换权限后再进行删除操作`)
		}
		const sql = 'delete from authority where authority_id=?'
		db.query(sql, req.body.authority_id, (err, results) => {
			if(err) return res.cc(err)
			res.cc('删除成功', 0)
		})
	})
}